package com.xuelang.pipeline.worker.client.pod.config;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xuelang.pipeline.worker.client.common.result.ApiResult;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import io.kubernetes.client.openapi.models.V1PodList;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * <p>节点服务Feign配置</p>
 *
 * @author : yixin.lys
 * @date : 2024-07-16 15:16
 **/
@Slf4j
public class PodFeignConfig implements Decoder {

    private final ObjectMapper objectMapper;

    public PodFeignConfig(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException {
        // 检查类型是否为 ApiResult<V1PodList>
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            if (parameterizedType.getRawType().equals(ApiResult.class)) {

                String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
                if(parameterizedType.getActualTypeArguments()[0].equals(V1PodList.class)) {
                    try {
                        // 使用泛型类型解析 ApiResult<V1PodList>
                        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ApiResult.class, V1PodList.class);
                        return objectMapper.readValue(bodyStr, javaType);
                    } catch (Exception e) {
                        log.error("Error decoding ApiResult<V1PodList>: {}", e.getMessage());
                        throw new DecodeException(response.status(), "Error decoding ApiResult<V1PodList>", response.request(), e);
                    }
                }
                if (parameterizedType.getActualTypeArguments()[0].equals(String.class)) {
                    try {
                        // 使用泛型类型解析 ApiResult<String>
                        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ApiResult.class, String.class);
                        return objectMapper.readValue(bodyStr, javaType);
                    } catch (Exception e) {
                        log.error("Error decoding ApiResult<String>: {}", e.getMessage());
                        throw new DecodeException(response.status(), "Error decoding ApiResult<String>", response.request(), e);
                    }
                }
            }
        }
        // 对于其他类型，使用默认解码器
        return new Decoder.Default().decode(response, type);
    }

}
